package log;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

import fr.inria.vit.LifecycleBehavior;

/**
 * A LogManager that automatically logs chunks of data at fixed frequency.
 * The default behavior is to keep the last logged value of each factor.
 * <br><br>
 * <code>writeLogLine()</code> is called automatically, it should be avoided in
 * normal use.
 * 
 * @author Mathieu Nancel
 *
 */
public class ChunkLogger extends LogManager implements LifecycleBehavior {
	
	protected int frequency;
	
	protected Timer timer;
	
	protected boolean started = false, paused = false;
	
	public ChunkLogger(String logName, String logFileName, boolean verbal, boolean log, int freq, String... logKeys) {
		super(logName, logFileName, verbal, log, logKeys);
		
		this.frequency = freq;
		
		timer = new Timer(frequency, new ActionListener() {
			
			public void actionPerformed(ActionEvent arg0) {
				
				atLog();
				
				// System.out.println("coin");
				writeLogLine(false, true);
				
			}
		});
		
		timer.setRepeats(true);
	}
	

	
	/**
	 * This method is called right before <code>writeLogLine()</code> and can be 
	 * overwritten if special, time dependent measures have to be added to the 
	 * log. 
	 */
	public void atLog() {}
	
	public boolean start() {
		
		if (!started) {
			
			timer.restart();
			
			if (verbal) {
				System.out.println(logName + " started");
			}
			
			started = true;
		}
		
		return started;
	}
	
	public void stop() {
		
		if (started) {
			
			timer.stop();
			
			if (verbal) {
				System.out.println(logName + " stopped");
			}
			
			started = false;
		}
		
	}
	
	public boolean isStarted() {
		return started;
	}
	
}
